import {
	getSettings
} from '@/api/system/user'
import store from '@/store'

function getTime(str) {
	const arr = str.split(":");
	return {
		h: +arr[0],
		min: +arr[1]
	};
}

function isRemind(times, h, min) {
	const item = times.find((item) => {
		const time = getTime(item);
		if (time.h === h && time.min === min) {
			return item;
		}
	});
	return item;
}

// 提醒
function remind(settings) {
	const type = settings.reminder.reminderMode || "alert";
	if (type.includes("alert")) {
		uni.showModal({
			title: '闹钟提醒',
			content: '记得及时进行眼睛锻炼哦',
		});
	}
	if (type.includes("vibrate") || type.includes("Vibrate")) {
		uni.vibrateLong();
	}
}

let timer;
let oldTime;

export function alarmReminder() {
	getSettings().then((res) => {
		const settings = res;
		timer && clearInterval(timer);
		let num = 0;
		timer = setInterval(() => {
			const date = new Date();
			const h = date.getHours(); // 获取小时
			const min = date.getMinutes(); // 获取分钟
			if (oldTime === "" + h + min) {
				return;
			}
			const times = settings.reminder.reminderTime || ["09:00", "13:00", "21:00"];
			// console.log(h, min, times);
			const flag = isRemind(times, h, min);
			if (flag) {
				oldTime = "" + h + min;
				remind(settings);
				clearInterval(timer);
			}
			num++;
			if (num >= 65) {
				oldTime = null;
			}
		}, 1000);
	});
}